package com.mervin.helper;

import com.mervin.annotation.LineFieldAnnotation;
import com.mervin.constant.Constants;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;

/***************************************
 * @author: mervin
 * @Date: 2020-05-04 13:08
 * @Description: 字段定长行的处理类
 ***************************************/
public class FixLengthParseProcess extends ParseProcess {

    @Override
    protected String getFieldStrVal(Field field, String line){
        int fieldStartIndex = getFieldStartIndex(field);
        int fieldEndIndex = getFieldEndIndex(field);
        return lineToFieldVal(line, fieldStartIndex, fieldEndIndex);
    }

    private int getFieldStartIndex(Field field){
        LineFieldAnnotation fieldAnnotation = field.getAnnotation(LineFieldAnnotation.class);
        return fieldAnnotation.startIndex();
    }

    private int getFieldEndIndex(Field field){
        LineFieldAnnotation fieldAnnotation = field.getAnnotation(LineFieldAnnotation.class);
        return fieldAnnotation.endIndex();
    }

    /**
     *
     * @param line
     * @param fieldStartIndex
     * @param fieldEndIndex
     * @return
     */
    private String lineToFieldVal(String line, int fieldStartIndex, int fieldEndIndex){
        int len = fieldEndIndex - fieldStartIndex + 1;
        byte[] byteArray = new byte[len];
        try {
            byteArray = line.getBytes(Constants.FILE_ENCODING_UTF8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] temp = new byte[len];
        System.arraycopy(byteArray, fieldStartIndex, temp, 0, len);
        return new String(temp);
    }
}
